package com.changgou.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.Util.IdWorker;
import com.changgou.seckill.config.ConfirmMessageSender;
import com.changgou.seckill.config.RabbitMQConfig;
import com.changgou.seckill.dao.SeckillOrderMapper;
import com.changgou.seckill.pojo.SeckillGoods;
import com.changgou.seckill.pojo.SeckillOrder;
import com.changgou.seckill.service.SeckillOrderService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class SeckillOrderServiceImpl implements SeckillOrderService {

    @Autowired
    private RedisTemplate redisTemplate;

    private static final String SECKILL_GOODS_KEY="seckill_goods_";

    private static final String SECKILL_GOODS_STOCK_COUNT_KEY="seckill_goods_stock_count_";

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private ConfirmMessageSender confirmMessageSender;

    @Autowired
    private SeckillOrderMapper seckillOrderMapper;

    @Override
    public boolean add(Long id, String time, String username) {

        //防止用户恶意刷单
        String result = this.preventRepeatCommit(username, id);
        if ("fail".equals(result)){
            return false;
        }

        //防止相同重复商品重复购买
        SeckillOrder order = seckillOrderMapper.getOrderInfoByUserNameAndGoodsId(username, id);
        if (order!=null){
            return false;
        }


        //获取redis 商品 库存的信息
        SeckillGoods seckillGoods = (SeckillGoods) redisTemplate.boundHashOps(SECKILL_GOODS_KEY + time).get(id);
        String redisStock = (String) redisTemplate.opsForValue().get(SECKILL_GOODS_STOCK_COUNT_KEY + id);
        if (StringUtils.isEmpty(redisStock)){
            return false;
        }
        int stock = Integer.parseInt(redisStock);
        if (seckillGoods==null||stock<=0){
            return false;
        }

        //执行redis预扣减库存  之后的数值

        Long decrement = redisTemplate.opsForValue().decrement(SECKILL_GOODS_STOCK_COUNT_KEY + id);
        if (decrement<=0){
            //没有库存
            //扣减之后的值 小于 等于 0 删除redis 商品 库存的信息
            redisTemplate.boundHashOps(SECKILL_GOODS_KEY + time).delete(id);
            redisTemplate.delete(SECKILL_GOODS_STOCK_COUNT_KEY + id);
    }

        //发送消息  (保证消息不丢失)
        SeckillOrder seckillOrder =new SeckillOrder();
        seckillOrder.setId(idWorker.nextId());
        seckillOrder.setSeckillId(id);
        seckillOrder.setMoney(seckillGoods.getCostPrice());
        seckillOrder.setUserId(username);
        seckillOrder.setSellerId(seckillGoods.getSellerId());
        seckillOrder.setCreateTime(new Date());
        seckillOrder.setStatus("0");

        //Mq 完成 mysql 数据同步  进行下单 扣减库存(mysql)
        confirmMessageSender.sendMessage("", RabbitMQConfig.SECKILL_ORDER_QUEUE, JSON.toJSONString(seckillOrder));

        return false;
    }

    private String preventRepeatCommit(String username,Long id){
        String redis_key = "seckill_user_"+username+"_id_"+id;

        long count = redisTemplate.opsForValue().increment(redis_key, 1);
        if (count==1){
            //第一次访问  设置5分钟有效期
            redisTemplate.expire(redis_key,5, TimeUnit.MINUTES);
            return "success";
        }
        if (count>1){
            return "fail";
        }

        return "fail";
    }
}
